"use strict";
define(["commonUI", "laydate", "template", "drawer","global", "validate", "select2", "datatables", "plupload"], function (
    commonUI, laydate, template, Drawer,global
) {
    var user = null;
    //传给后台的参数
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var globalProjectId = null;
    var table21 = "";
    var sysClassTable = null;
    var app = {
        init: function () {
            user = global.getLoginUser();
            $(".username").text(user.userName)
            this.eventBind();
            this.renderTable();
            this.intDrawer();
        },
        // 渲染表格
        renderTable: function () {
            table21 = $('#standard_table').DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                ordering: true,
                serverSide: true,
                destroy: true,
                // scrollX: true,
                columns: [{
                    title: '<div id="select-checkbox" class="select-checkbox1"></div>',
                    data: "checkBox",
                    width: 20,
                    render:function(){
                        return '';
                    }
                }, {
                    title: '序号',
                    data: "number",
                    width: 30
                }, {
                    title: '项目ID',
                    data: "identification",
                    width: 50
                }, {
                    title: '项目名称',
                    data: "name",
                    width: 70
                }, {
                    title: '所在地区',
                    data: "city",
                    width: 60
                }, {
                    title: '建筑面积（万平方米）',
                    data: "area",
                    width: 100

                }, {
                    title: '当前模式',
                    data: "mode",
                    width: 60,
                    render:function(data){
                        if(data==1){
                            return "供暖季节"
                        }else if(data==0){
                            return "制冷季节"
                        }else{
                            return "错误代码"
                        }
                    }

                }, {
                    title: '项目起始时间',
                    data: "createTime",
                    width: 100

                }, {
                    title: '操作',
                    width: 200,
                    render: function (data, type, full) {
                        return '<a class="classify" data-id="' + full.id + '">系统分类</a>' +
                            '<a class="edit" data-id="' + full.id + '">编辑</a>' +
                            '<a class="del-single" data-id="' + full.id + '">删除</a>' +
                            '<a class="show-pic" data-id="' + full.id + '">显示图</a>'  +
                            '<a class="equipment-check" href="equipmentCheck.html?projectId='+full.id+'" target="_blank">设备位置配置</a>';
                    },
                }],
                lengthMenu: [[15, 25, 50, 100], ["15条/页", "25条/页", "50条/页", "100条/页"]],
                columnDefs: [{
                    className: 'select-checkbox ',
                    targets: 0
                }, {
                    orderable: false,
                    targets: [0, 1, 2, 3, 4, 5, 6, 8]
                }, {
                    targets: [2, 3, 4, 5, 6, 7],
                    render: function (data) {//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                select: {
                    // 可选择的配置有： 'api'、'single'、'multi'、'os'、'multi+shift'
                    style: 'multi',
                    // 控制是否在左下角显示选中信息
                    info: false,
                    selector: 'td:first-child',
                    orderable: false
                },
                order: [],
                language: {
                    sEmptyTable: '<div class="blank-icon"><p class="msg"><i class="aidicon aidicon-emoticon-sad"></i> 没有搜到任何数据</p></div>'
                },
                ajax: function (params, callback, setting) {
                    // 表格逻辑
                    $('#standard_table_wrapper thead>tr>.select-checkbox').removeClass('selected');
                    $("#delete_all").prop("disabled", true);
                    //排序参数
                    var sortType = "",
                        sortName = "";
                    if (params.order.length > 0) {
                        sortType = params.order[0].dir;
                        sortName = params.columns[params.order[0].column].data;
                    }
                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.keyword = $("#search_val").val()
                    global.get("/admin/project/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {
                    var html = '<li data-curIndex="all" class="all-col"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">全部展示</span></label></div></li>';
                    for (var i = 0; i < settings.aoColumns.length; i++) {
                        if (i == 0) {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">勾选列</span></label></div></li>';
                        } else {
                            html += '<li data-curIndex="' + i + '"><div class="checkbox"><label class="checkbox-beauty"><input type="checkbox" checked> <span class="text-label">' + settings.aoColumns[i].sTitle + '</span></label></div></li>';
                        }

                    }
                    $(".dropdown-col-menu").append(html);
                    $('.dropdown-col-menu>li input').change(function () {
                        if ($(this).closest('li').attr('data-curIndex') == "all") { //点击全部
                            if ($(this).is(':checked')) {
                                table21.columns().visible(true);
                                $(this).closest('li').siblings('li').find('input').prop("checked", true)
                            } else {
                                table21.columns().visible(false);
                                $(this).closest('li').siblings('li').find('input').prop("checked", false)
                            }
                        } else { //点击每一列
                            var _index = parseInt($(this).closest('li').attr('data-curIndex'), 10);
                            if ($(this).is(':checked')) {
                                table21.columns(_index).visible(true);
                            } else {
                                table21.columns(_index).visible(false);
                            }

                            // 控制全选的样式
                            var colLength = table21.columns().count();
                            var colSelect = $('.dropdown-col-menu > li[data-curIndex != all] input:checked').length;
                            if (colSelect == colLength) {
                                $('.dropdown-col-menu .all-col input').prop("checked", true);
                            } else {
                                $('.dropdown-col-menu .all-col input').prop("checked", false);
                            }
                        }
                    });

                    //计算列定制下拉的位置
                    var leftPx = "-" + ($(".dropdown-col-menu").width() - 30) + "px";
                    $(".dropdown-col-menu").css("left", leftPx);

                }
            });

            // 去掉选中
            table21.on('deselect', function (e, dt, type, indexs) {
                // $(e.target).find('thead>tr>.select-checkbox').removeClass('selected');
                $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').removeClass('selected');
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                if (selectedLength == 0) {
                    $("#export").prop("disabled", true);
                    $("#delete_all").prop("disabled", true);
                    $(".dropdown-opt-con .btn").prop("disabled", true);
                }
            });
            // 点击全选
            $('#standard_table_wrapper .select-checkbox1').click(function (e) {

                var $parent = $(this).parent('th');
                $parent.toggleClass('selected');
                if ($parent.hasClass('selected')) {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select()
                    });
                } else {
                    $(this).parents('#standard_table_wrapper').find('tbody tr').each(function (i) {
                        table21.row(i).select(false)
                    });
                }
            });
            // 勾选其中一项
            table21.on('select', function (e, dt, type, indexs) {
                // 选中行数
                var selectedLength = table21.rows({
                    selected: true
                }).count();
                $("#export").prop("disabled", false);
                $("#delete_all").prop("disabled", false);
                $(".dropdown-opt-con .btn").prop("disabled", false);
                // 所有行数行数
                var allLength = table21.rows().count();
                // selectedLength === allLength && $(e.target).find('thead>tr>.select-checkbox').addClass('selected');
                selectedLength === allLength && $(e.target).closest('.dataTables_scroll').find('.dataTables_scrollHead').find('thead>tr>.select-checkbox').addClass('selected');
            });
        },
        //抽屉
        intDrawer: function () {
            // 新增抽屉
            var addDrawerOpts = {
                title: "",
                data: {
                },
                content: template("addFormTpl"),
                onClosed:function () {
                },
                button: [
                    {
                        label: "取消",
                        intent: "default",
                        click:function () {
                            app.addDrawer.close();
                        }
                    },
                    {
                        label: "提交",
                        intent: "primary",
                        click: function () {
                            if (!$(".addForm").valid()) {
                                return false;
                            }
                            var data= {};
                            data.id = $("#id").val()
                            data.name =$("#name").val()
                            data.identification =$("#identification").val()
                            data.city = $("#city").val() 
                            data.createTime = $("#createTime").val()
                            data.area = $("#area").val()
                            data.description = $("#description").val()
                            data.maxColdLoad = $("#maxColdLoad").val()
                            data.maxHotLoad = $("#maxHotLoad").val()
                            data.panelX=$("#panelX").val()
                            data.panelY=$("#panelY").val()
                            data.mode =$("input[name='mode']:checked").val();
                            data.heatPumpCapacity = $("#heatPumpCapacity").val();
                            data.isRemoted=$("#isRemoted").is(":checked")?1:0;
                            if(data.isRemoted===1){
                                data.topic=$("#topic").val();
                                data.temperatureSettingTag=$("#temperatureSettingTag").val();
                                data.startStopTag=$("#startStopTag").val();
                                data.summerWinnerTag=$("#summerWinnerTag").val();
                            }else{
                                data.topic="";
                                data.temperatureSettingTag="";
                                data.startStopTag="";
                                data.summerWinnerTag="";
                            }
                            global.post("/admin/project/saveOrUpdate",response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    }
                ]
            };
            app.addDrawer = new Drawer(addDrawerOpts);
        },
        // 系统分类列表
        initClassifyTable: function (projectId) {
            var sysclasses = [];
            global.get("/admin/project/sysclass/list/"+projectId,function (res) {
                if (res.success) {
                    sysclasses = res.data.sysclasses;
                }
            },null,null,false);
            sysClassTable=$('#grid-demo-1').DataTable({
                data: sysclasses,
                deferRender: true,
                destroy: true,
                paging: false,
                searching: false,
                info: false,
                ordering: false,
                scrollY: 380,
                scrollCollapse: true,
                language: {
                    sEmptyTable: '<div class="blank-icon"><p class="msg"><i class="aidicon aidicon-emoticon-sad"></i> 没有搜到任何数据</p></div>'
                },
                columns: [
                    {
                        title: "系统分类名称",
                        data: "className",
                        width: "70%",
                        render: function (data) {
                            if (data) {
                                return "<div class='text-overflow' title='" + data + "'>" + data + "</div>";
                            } else {
                                return "-";
                            }
                        }
                    },
                    {
                        title: "操作",
                        data: "id",
                        width: "30%",
                        render: function (data, type, full) {
                            return '<a class="classify-edit" data-id="' + full.id + '" data-name="'+full.className+'" data-toggle="modal" data-target="#editModal">修改</a>' +
                                    '<a class="classify-del" data-id="' + full.id + '" id="popover-' + full.id + '" data-toggle="popover" data-placement="auto top">删除</a>';
                        },
                    }
                ],
                initComplete: function(settings, json) {
                    $('[data-toggle="popover"]').each(function(i,v) {
                        var id = $(v).data("id");
                        $(v).popover({
                            html: true,
                            container: 'body',
                            // container: window.top.document.body,
                            content: '<div style="line-height:16px;">' +
                                '<i class="aidicon aidicon-close-circle" style="float:left;line-height:16px;margin-right:5px;color:#F53B3B;"></i>' +
                                '<span>你确定要删除这项内容吗？</span>' +
                                '<div class="text-right margin-top-small-2">' +
                                '<button  type="button" class="cancel btn btn-default btn-sm margin-right-small-2">取消</button>' +
                                '<button  type="button" class="btn btn-primary btn-sm delete-classify" data-id="'+id+'">确定</button>' +
                                '</div>'
                        });
                    })
                    
                }
            });
        },
        // 文件上传
        initUploader1: function(id) {
            //实例化一个plupload上传对象  
            var uploader3 = new plupload.Uploader({  
                //触发文件选择对话框的按钮，为那个元素id  
                browse_button : 'chose_file3', 
                multi_selection: false,
                //服务器端的上传页面地址  
                url : global.baseUrl + "/admin/project/image/upload?type="+(id-1) + "&projectId="+globalProjectId 
            });      

            //当文件添加到上传队列后触发  
            uploader3.bind('FilesAdded',function(uploader,files){  
                var progress = '<div class="upload-wrap" data-wrap-id="'+ files[0].id +'">'+
                    '<div>'+ files[0].name+'</div>'+
                    '<div class="progress progress-ty" data-id="'+ files[0].id +'">'+
                        '<div class="progress-bars">'+
                            '<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'+
                            '</div>'+    
                        '</div>'+
                        '<span class="progress-percent">0%</span>'+
                    '</div>'+
                    '<a class="file-uploaded-delete" data-id="'+ files[0].id +'" >删除</a>'+
                '</div>';
                var $progress = $(progress);
                $('#progressDemo1').append($progress);
                uploader.start();  
            });  

            //当队列中的某一个文件上传完成后触发  
            uploader3.bind('FileUploaded',function(uploader,file,responseObject){  
                $('.upload-wrap[data-wrap-id="'+ file.id +'"]').addClass('uploadSuccess');
                console.log("上传成功！");
                $("#chose_file3").attr("disabled", true);
            });  

            //会在文件上传过程中不断触发，可以用此事件来显示上传进度  
            uploader3.bind('UploadProgress',function(uploader,file){  
                var $dom = $('[data-id="'+ file.id +'"]');
                //显示进度
                var percent = file.percent; 
                $dom.find('.progress-bar').attr('aria-valuenow',percent);
                $dom.find('.progress-bar').width(percent +'%');
                $dom.find('.progress-percent').html(percent +'%');
            });  

            // 上传失败时触发
            uploader3.bind('Error',function(uploader,errObject){  
                var $dom = $('.upload-wrap[data-wrap-id="'+ errObject.file.id +'"]');
                $dom.find('.progress-bar').addClass('progress-bar-danger');
            })

            // 删除远程图片
            $('#progressDemo1').on('click','.file-uploaded-delete',function(e){
                // alert('删除远程图片');
                $(this).parents(".upload-wrap").remove();
                $("#chose_file3").removeAttr("disabled");
            })
            //在实例对象上调用init()方法进行初始化  
            uploader3.init();
        },
        // 图片上传
        initUploader2: function (id) {
            // 用于记录上传速度，上传速度过快则加载过程动画无法显示，需要在加载完成方法中进行动画模拟    
            var timer = 0;

            //实例化一个plupload上传对象  
            var uploader8 = new plupload.Uploader({  
                //触发文件选择对话框的按钮，为那个元素id  
                browse_button : 'photoUploadMulti'+id, 
                multi_selection: false,
                filters: {
                    mime_types : [ 
                        { title : "Image files", extensions : "jpg,png,jpeg" }
                    ],
                },
                //服务器端的上传页面地址  
                url : global.baseUrl + "/admin/project/image/upload?type="+(id-1) + "&projectId="+globalProjectId
            });      

            //当文件添加到上传队列后触发  
            uploader8.bind('FilesAdded',function(uploader,files){  
                var img = new moxie.image.Image();
                img.onload = function(){
                    var $img = $('<li class="photoUpload-li" data-id="'+ files[0].id +'"><div class="photoUpload-li-img-wrapper"><img class="photoUpload-li-img" src="'+ this.getAsDataURL()+'"/></div><div class="photoUpload-loading-wrap"><canvas id="photoUpload-loading"></canvas></div><i class="aidicon aidicon-close-circle photoUpload-delete"></i></li>');
                    $img.insertBefore($('#photoUploadMulti'+id));
                    uploader.start();  
                }
                img.load(files[0].getSource())
            });  

            //当队列中的某一个文件上传完成后触发  
            uploader8.bind('FileUploaded',function(uploader,file,responseObject){  
                // 触发上传进度次数太少时,模拟触发上传进度动画
                if(timer < 20){
                    var $dom = $('[data-id="'+ file.id +'"] #photoUpload-loading');
                    var STEP = 5;
                    var animate = function ($dom, percent) {
                        requestAnimationFrame(function () {
                            percent = percent + STEP;
                            uploadImage( $dom,percent);
                            if(percent < 100){
                                animate($dom,percent)
                            }else{
                                // 动画结束隐藏遮罩层
                                $dom.css('display','none');
                            }
                        });
                    };
                    animate($dom,0);
                }else{
                    // 动画结束隐藏遮罩层
                    $dom.css('display','none');
                }
                console.log("上传成功！");
                $dom.parents(".photoUpload-li").siblings(".photoUpload").hide();
            });  

            //会在文件上传过程中不断触发，可以用此事件来显示上传进度  
            uploader8.bind('UploadProgress',function(uploader,file){  
                timer++;
                var $dom = $('#progressDemo'+id+' [data-id="'+ file.id +'"] #photoUpload-loading');
                //显示进度
                var percent = file.percent; 
                uploadImage($dom,percent);
            });  

            // 绘制上传进度
            function uploadImage($canvas,percent){
                var c = $canvas[0];
                var ctx = c.getContext('2d');
                var drawCricle = function (ctx, percent) {
                    ctx.beginPath();
                    ctx.moveTo(c.width / 2, c.height / 2);
                    ctx.clearRect(0, 0, c.width, c.height);
                    ctx.arc(c.width / 2, c.width / 2, c.width / 2, Math.PI * 1.5, Math.PI * (1.5 + 2 * percent / 100 ), true);
                    ctx.closePath();
                    ctx.fillStyle = 'rgba(14,16,17,0.4)';
                    ctx.fill();
                };
                drawCricle(ctx, percent, true);
            }

            $(document).on('mouseover','#progressDemo'+id+' .photoUpload-loading-wrap,#progressDemo'+id+' .reUpload,#progressDemo'+id+' .photoUpload-delete',function(e){
                $(this).parent().addClass('photoUpload-active');
            })
            $(document).on('mouseout','#progressDemo'+id+' .photoUpload-loading-wrap,#progressDemo'+id+' .reUpload,#progressDemo'+id+' .photoUpload-delete',function(e){
                $(this).parent().removeClass('photoUpload-active');
            })
            $(document).on('click','#progressDemo'+id+' .photoUpload-delete',function(e){
                // TODO
                // alert('删除文件')
                $(this).parents(".photoUpload-li").siblings(".photoUpload").show();
                $(this).parents(".photoUpload-li").remove();
            })
            $(document).on('click','#progressDemo'+id+' .reUpload',function(e){
                // TODO
                // alert('重新上传')
                $(this).parents(".photoUpload-li").siblings(".photoUpload").trigger("click");
            })

            //在实例对象上调用init()方法进行初始化  
            uploader8.init();
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增
            $('#add').on('click', function () {
                var content = template("addFormTpl", {data:{mode:0}});
                app.addDrawer.renderOption({title: "新增项目信息",content:content});
                app.addDrawer.open();
                laydate.render({
                    elem:'#createTime',
                    type:'date',
                    eventElem: '.dateicon',
                    trigger: 'click',
                    showBottom: true
                });
            });
            // 编辑
            $(document).on("click", ".edit", function () {
                var id = $(this).attr("data-id");
                global.get("/admin/project/"+id,response=>{
                    var project = response.data.project;
                    var editInfo = project;
                    var content = template("addFormTpl", {data: editInfo});
                    app.addDrawer.renderOption({title: "修改项目信息", content: content});
                    app.addDrawer.open();
                    laydate.render({
                        elem:'#createTime',
                        type:'date',
                        eventElem: '.dateicon',
                        trigger: 'click',
                        showBottom: true
                    });
                    if(editInfo.isRemoted===true){
                        $('#isRemoted').prop("checked",true)
                        $('.control-content').show()
                    }else{
                        $('.control-content').hide()
                    }
                })
            });
            // 单个删除
            $(document).on('click', ".del-single", function () {
                var id = $(this).attr("data-id");
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确定删除该信息吗？</span>",
                    width: 320,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5">您确定要删除吗？删除后状态不可恢复。</div>',
                    button: [
                        { id: "mybtn1", label: "确认", intent: "primary", focus: true, click: function () {
                            global.delete("/admin/project/delete/"+id,response=>{
                                if(response.success){
                                    app.addDrawer.close();
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message);
                                }
                            })
                         } },
                        { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                });
            });
            // 批量删除
            $(document).on('click', "#delete_all", function () {
                Dialog.open({
                    id: "delete_all_dialog",
                    theme: "simple-dialog",
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>您确定要删除所选内容吗？</span>",
                    width: 420,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5"><div class="font-color-weak padding-horizontal-large-2 padding-bottom-large-2">删除后的数据将无法恢复</div></div>',
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var pripidDom = table21.rows('.selected').data()
                            var ids = [];
                            Array.prototype.slice.call(pripidDom).forEach(function(v, i) {
                                ids.push(v.id);
                            });
                            global.delete("/admin/project/deletems/"+ids.join("&"),response=>{
                                if(response.success){
                                    table21.ajax.reload(null,false);
                                }else{
                                    alert(response.message);
                                }
                            })
                            // pripidDom.forEach(item=>{
                            //     console.log(item);
                            // })
                            //     taskIdArr = [],
                            //     taskNameArr = [];
                            
                            
                            // var param = {
                            //     taskId: taskIdArr.join(","),
                            //     taskName: taskNameArr.join(",")
                            // };
                            // $.ajax({
                            //     url: "",
                            //     type: "get",
                            //     data: param,
                            //     dataType: "json",
                            //     success: function(res) {
                            //         table21.ajax.reload();
                            //     }
                            // });
                        }
                    }, {
                        id: "mybtn2",
                        label: "取消",
                        click: function () {

                        }
                    }]
                });
            });
            // 系统分类
            $(document).on("click", ".classify", function () {
                var projectId = $(this).data("id");
                globalProjectId = projectId;
                Dialog.open({
                    theme: "classifyDialog",
                    id: 'dialog-example11',
                    title: '系统分类',
                    width: 582,
                    height: 600,
                    modal: true,
                    context: self,
                    content: template("classifyTpl"),
                    onShow: function () {
                        app.initClassifyTable(projectId);
                    },
                    onClosed: function () {
                    }
                });
            });
            // 展示图
            $(document).on("click", ".show-pic", function () {
                globalProjectId = $(this).attr("data-id");
                Dialog.open({
                    theme: "imgDialog",
                    id: 'dialog-example11',
                    title: '显示图配置',
                    width: 582,
                    height: 530,
                    modal: true,
                    context: self,
                    content: template("imgTpl"),
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            // 确定编辑逻辑
                        }
                    }, {
                        id: "mybtn3",
                        label: "取消",
                        click: function () {
                            // 取消编辑逻辑
                        }
                    }],
                    onShow: function () {
                        app.initUploader1(1);
                        app.initUploader2(2);
                    },
                    onClosed: function () {
                    }
                });
            });
            // 搜索筛选
            $("#search-icon").on("click", function () {
                var searchVal = $("#search_val").val();
                console.log(searchVal);
                param.keyword = searchVal;
                table21.ajax.reload();
            });
            $("#search_val").on("keyup", function (event) {
                if (event.keyCode == "13") {
                    var searchVal = $("#search_val").val();
                    console.log(searchVal);
                    param.keyword = searchVal;
                    table21.ajax.reload();
                }
            });
            //去掉搜索框内容
            $('.searchbox .aidicon-close').on('mousedown', function () {
                $(this).siblings('input').val('');
            });
            // 点击气泡中的取消
            $(document).on("click", ".cancel", function() {
                $(this).parents(".popover").remove();
            });
            // 点击气泡中的确定
            $(document).on("click", ".delete-classify", function(e) {
                var id = $(this).data("id");
                global.delete("/admin/project/sysclass/" + id,function(res){
                    if(res.success){
                        app.initClassifyTable(globalProjectId);
                    }else{  
                        alert(res.message);
                    }
                })
                $(this).parents(".popover").remove();
            });
            //点击页面关闭弹出
            $(document).on('click', function(e) {
                // 点击页面其他地方关闭气泡
                $('[data-toggle="popover"]').each(function() {
                    if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                        (($(this).popover('hide').data('bs.popover') || {}).inState || {}).click = false
                    }
                });
            });
            $(document).on('click','.classify-edit',function(e){
                var sysClassId =$(this).attr("data-id");
                var sysClassName =$(this).attr("data-name");
                $("#sysClassId").val(sysClassId)
                $("#sysClassName").val(sysClassName)
            })
            $(document).on('click','#addClassify',function(e){
                $("#sysClassId").val(null)
                $("#sysClassName").val(null)
            })
            $(document).on('click',".saveOrUpdateClassName",function(e){
                var sysClassId =$("#sysClassId").val()
                var sysClassName =$("#sysClassName").val()
                var data = {};
                data.id = sysClassId;
                data.projectId = globalProjectId;
                data.className=sysClassName;
                global.post("/admin/project/sysclass/saveOrUpdate",function(res){
                    if(res.success){
                        $('#editModal').modal('hide');
                        app.initClassifyTable(globalProjectId);
                    }else{
                        alert(res.message)
                    }
                },JSON.stringify(data));

            })
            // 系统分类编辑
            $(document).on('show.bs.modal','#editModal', function(e) {
                console.log(e.relatedTarget.dataset["id"]);
                var name = e.relatedTarget.dataset["name"];
                $("#editModal #className").val(name);
            })
            // 启用状态切换
            $(document).on('click','#control-btn', function(){
                if($(this).find('input[type="checkbox"]').attr('data-state')==='on') {
                    $('.control-content').show()
                } else {
                    $('.control-content').hide()
                }
            })
        }

    };
    return app;
});